package pendotech.com.pendootg;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.pendotech.pendonoteotgcontroller.PendoNoteOtgController;
import com.pendotech.pendonoteotgcontroller.PendoNoteOtgControllerCallBack;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private TextView  text_log;

    private PendoNoteOtgController pendoNoteOtgController;

    private Button searchDevice_btn,disconnectDevice_btn,connectDevice_btn,clean_btn,mouse_btn,point_btn,double_btn;

    private MyCanvasView canvas_sv;

    private String point;

    private int offset;






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_main);

        text_log=findViewById(R.id.text_log);
        text_log.setMovementMethod(ScrollingMovementMethod.getInstance());

        searchDevice_btn=findViewById(R.id.searchDevice_btn);
        disconnectDevice_btn=findViewById(R.id.disconnectDevice_btn);
        connectDevice_btn=findViewById(R.id.connectDevice_btn);
        clean_btn=findViewById(R.id.clean_btn);

        double_btn=findViewById(R.id.double_btn);
        double_btn.setOnClickListener(this);

        mouse_btn=findViewById(R.id.mouse_btn);
        mouse_btn.setOnClickListener(this);

        point_btn=findViewById(R.id.point_btn);
        point_btn.setOnClickListener(this);





        canvas_sv=findViewById(R.id.canvas_sv);
        //canvas_sv.setPenColor(R.color.black);



        connectDevice_btn.setOnClickListener(this);
        searchDevice_btn.setOnClickListener(this);
        disconnectDevice_btn.setOnClickListener(this);
        clean_btn.setOnClickListener(this);


        //控制器  各种任务方法提供调用
        pendoNoteOtgController = PendoNoteOtgController.getInstance();
        //如果主动断开连接,需要重新注册services
        pendoNoteOtgController.prepareServices(MainActivity.this,controllerCallBack,PendoNoteOtgController.ON_CREATE);

        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},REQUESTPER_CODE);

    }


    private int REQUESTPER_CODE=11;


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==REQUESTPER_CODE){
               if (grantResults.length>0){

               }else {
                   Toast.makeText(this,"拒绝了文件读取权限，可能会导致升级mcu失败",Toast.LENGTH_SHORT).show();
               }
        }
    }

    private int[] location = new int[2];


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.searchDevice_btn:
                pendoNoteOtgController.searchHIDDevice();
                canvas_sv.getLocationInWindow(location);
                break;
            case R.id.connectDevice_btn:
                pendoNoteOtgController.connectDevice(0x2d80);

                break;
            case R.id.disconnectDevice_btn:
                //主动断开连接
                pendoNoteOtgController.closeConnection(this);

                //控制器  各种任务方法提供调用
                pendoNoteOtgController = PendoNoteOtgController.getInstance();
                //如果主动断开连接,需要重新注册services
                pendoNoteOtgController.prepareServices(MainActivity.this,controllerCallBack,PendoNoteOtgController.ON_CREATE);


                break;
            case R.id.clean_btn:
                    text_log.setText("");
                    canvas_sv.clear();
                break;
            case R.id.point_btn:
                pendoNoteOtgController.setPointMode();

                break;
            case R.id.mouse_btn:
                pendoNoteOtgController.setMouseMode();
                break;
            case R.id.double_btn:
                pendoNoteOtgController.setDoubleMode();
                break;



        }

    }




    PendoNoteOtgControllerCallBack controllerCallBack=new PendoNoteOtgControllerCallBack(){

        @Override
        public void onDeviceDisconnect() {
            super.onDeviceDisconnect();
            text_log.append("---onDeviceDisconnect---\n");

        }

        @Override
        public void onCheckDeviceState(Boolean isConnect){
            super.onCheckDeviceState(isConnect);
            if (isConnect){
                text_log.append("---onDeviceConnected---\n");
            }else{
                text_log.append("---onDeviceDisconnect---\n");
            }

        }




        @Override
        public void onGetDeviceList(CharSequence[] devicesName, boolean isSuccess) {
            super.onGetDeviceList(devicesName, isSuccess);
            text_log.append("---"+devicesName[0].toString()+"\n");

            connectDevice_btn.performClick();
        }



        @Override
        public void onDeviceConnected(boolean isSuccess) {
            super.onDeviceConnected(isSuccess);
            if (isSuccess){
                text_log.append("---onDeviceConnected success---\n");
                pendoNoteOtgController.setPointMode();
            }else{
                text_log.append("---onDeviceConnected fail---\n");
            }
        }

        @Override
        public void onGetRealTimePoints(int X, int Y, int P, int pMax) {
            super.onGetRealTimePoints(X, Y, P, pMax);

            Log.i("points",X+"---"+Y+"---"+P+"--"+canvas_sv.getWidth()+"--"+canvas_sv.getHeight());

            point="points:"+X+"---"+Y+"---"+P+"\n";
            text_log.append(point);

            X=X*1920/25600;   // 1920 1080  表示屏幕分辨率     25600为X最大值  14400为Y最大值
            Y=Y*1080/14400;    // 16800* 10500   小板子



            Log.i("points1",X+"---"+Y+"---"+P+"--"+canvas_sv.getWidth()+"--"+canvas_sv.getHeight());


             //限制只在绿色区域画线    location 代表 绿色画板相对屏幕左上角偏移量
            //if ((X>location[0]&&X<location[0]+canvas_sv.getWidth())&&(Y>location[1]&&Y<canvas_sv.getHeight()+location[1])){
                //myPoints.add(new MyPoint(X,Y,P));
                canvas_sv.hypenRealtimEvent(X-location[0],Y-location[1],P);
            //}



            offset=text_log.getLineCount()*text_log.getLineHeight();
            if(offset>text_log.getHeight()){
                text_log.scrollTo(0,offset-text_log.getHeight());
            }


        }


    };




    public static void saveBitmap(Bitmap bm) {
        Log.e("TAG", "保存图片");
        String tmpFile = "/sdcard/sign.png";
        File f = new File(tmpFile);

        if (f.exists())
            f.delete();
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.i("TAG", "已经保存");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {


        return super.onTouchEvent(event);
    }
}


